package cn.wolfcode.web.controller;

import cn.wolfcode.anno.RequiredPermission;
import cn.wolfcode.domain.Work;
import cn.wolfcode.domain.WorkJob;
import cn.wolfcode.query.JSONResult;
import cn.wolfcode.query.QueryObject;
import cn.wolfcode.query.WorkQueryObject;
import cn.wolfcode.service.IWorkJobService;
import cn.wolfcode.service.IWorkService;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


@Controller // 标识一下 可以被扫描 创建对象 加入spring容器
@RequestMapping("/work") // 访问路径的映射地址   作用 ： 可以通过浏览器 进行访问的地址
public class WorkController {


    @Autowired// 自动装配  WorkService
    private IWorkService workService;

    @Autowired// 自动装配   WorkService
    private IWorkJobService workJobService;

    // 想让浏览器直接访问的
    @RequestMapping("/list")  // 类上面的requestMapping的内容 + 方法上面的requestMapping的内容
    // 这两个映射地址拼接起来 才是找到这个方法的真实路径
    //      // currentPage  表示接收 页面上提交的参数
    @RequiredPermission({"轮岗列表权限", "WorkController.list"})
    public String list(Model model, @ModelAttribute("qo") WorkQueryObject qo) {  // 返回值是String   返回值的内容 一般是一个地址
        PageInfo pageInfo = workService.findAll(qo);
        // 把数据共享给页面
        model.addAttribute("pageInfo", pageInfo);
        return "/work/list";
    }

    @RequestMapping("/delete")
    @ResponseBody
    @RequiredPermission({"轮岗删除权限", "WorkController.delete"})
    public JSONResult delete(Long id) {
        try {
            workService.deleteById(id);
            return new JSONResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONResult().mark("删除失败，请稍后重试");
        }
    }

    @RequestMapping("/input")
    @RequiredPermission({"轮岗添加权限", "WorkController.input"})
    public String input(Long id, Model model) {
        List<WorkJob> workJobs = workJobService.listAll();
        model.addAttribute("workJobs", workJobs);
        if (id != null) {
            //根据id获取轮岗信息
            Work Work = workService.findById(id);
            //把数据共享到页面
            model.addAttribute("entity", Work);
        }
        return "/work/input";
    }

    @RequestMapping("/saveOrUpdate")
    @RequiredPermission({"轮岗更新权限", "WorkController.saveOrUpdate"})
    public String saveOrUpdate(Work Work) {
        workService.saveOrUpdate(Work);
        return "redirect:/work/list";
    }//redirect重定向

    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition","attachment;filename=work.xls");
        List<Work> works = workService.listAll();

        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("员工");
        Row firstRow = sheet.createRow(0);
        firstRow.createCell(0).setCellValue("姓名");
        firstRow.createCell(1).setCellValue("性别");
        firstRow.createCell(2).setCellValue("年龄");
        firstRow.createCell(3).setCellValue("电话号码");
        firstRow.createCell(4).setCellValue("所属单位");
        firstRow.createCell(5).setCellValue("所属职务");
        firstRow.createCell(6).setCellValue("上轮轮岗日期");
        firstRow.createCell(7).setCellValue("本轮轮岗日期");
        firstRow.createCell(8).setCellValue("剩余天数");

        for(int i=0;i<works.size();i++){
            Row row = sheet.createRow(i + 1);
            Work work = works.get(i);

            row.createCell(0).setCellValue(work.getName());
            row.createCell(1).setCellValue(work.getSexToString());
            row.createCell(2).setCellValue(work.getAge());
            row.createCell(3).setCellValue(work.getPhone_number());
            row.createCell(4).setCellValue(work.getUnit());
            row.createCell(5).setCellValue(work.getJob().getName());
            row.createCell(6).setCellValue(work.getLast_date());
            row.createCell(7).setCellValue(work.getNow_date());
            row.createCell(8).setCellValue(work.getRemain());
        }
        workbook.write(response.getOutputStream());
    }

    @RequestMapping("/importXls")
    public String importXls(MultipartFile multipartFile) throws IOException {

        Workbook workbook = WorkbookFactory.create(multipartFile.getInputStream());
        Sheet sheet = workbook.getSheetAt(0);

        int lastRowNum = sheet.getLastRowNum();

        for(int i=1;i<=lastRowNum;i++){
            Row row = sheet.getRow(i);
            String username = row.getCell(0).getStringCellValue();
            String sex = row.getCell(1).getStringCellValue();
            boolean isSex = true;
            if(sex.equals("男")){
                isSex = true;
            }else{
                isSex = false;
            }

            int age = (int)row.getCell(2).getNumericCellValue();
            String phoneNumber = row.getCell(3).getStringCellValue();
            String unit = row.getCell(4).getStringCellValue();
            String job = row.getCell(5).getStringCellValue();
            Date lastDate = row.getCell(6).getDateCellValue();

            Work work = new Work();
            work.setName(username);
            work.setSex(isSex);
            work.setAge(age);
            work.setPhone_number(phoneNumber);
            work.setUnit(unit);

            WorkJob workJob = workJobService.getWorkJobByName(job);
            work.setJob(workJob);
            work.setLast_date(new java.sql.Date(lastDate.getTime()));

            Calendar cal = Calendar.getInstance();
            cal.setTime(new java.sql.Date(lastDate.getTime()));//设置时间
            cal.add(Calendar.YEAR, workJob.getAge());//增加年限

            work.setNow_date(new java.sql.Date(cal.getTime().getTime()));
            workService.saveOrUpdate(work);
        }
        return "redirect:/work/list";

    }
}





